define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'task/task/index',
                    add_url: 'task/task/add',
                    edit_url: 'task/task/edit',
                    del_url: 'task/task/del',
                    multi_url: 'task/task/multi',
                    view_detail_url: 'task/job/index',
                    start_task_url: 'task/task/start',
                    pause_task_url: 'task/task/pause',
                    stop_task_url: 'task/task/stop',
                    retry_task_url: 'task/task/retry',
                    table: 'task',
                }
            });

            var table = $("#table");

            // 批量操作请求
            var multi = function (action, ids, table, element) {
                var options = table.bootstrapTable('getOptions');
                var data = element ? $(element).data() : {};
                var ids = ($.isArray(ids) ? ids.join(",") : ids);
                var action_url = '';
                switch (action) {
                    case 'stop':
                        action_url = options.extend.stop_task_url;
                        break;
                    case 'start':
                        action_url = options.extend.start_task_url;
                        break;
                    case 'pause':
                        action_url = options.extend.pause_task_url;
                        break;
                    case 'retry':
                        action_url = options.extend.retry_task_url;
                        break;
                }
                var url = typeof data.url !== "undefined" ? data.url : (action_url != "" ? action_url : options.extend.multi_url);
                url = Table.api.replaceurl(url, {
                    ids: ids
                }, table);
                var params = typeof data.params !== "undefined" ? (typeof data.params == 'object' ? $.param(data.params) : data.params) : '';
                var options = {
                    url: url,
                    data: {
                        action: action,
                        ids: ids,
                        params: params
                    }
                };
                Fast.api.ajax(options, function (data, ret) {
                    var success = $(element).data("success") || $.noop;
                    if (typeof success === 'function') {
                        if (false === success.call(element, data, ret)) {
                            return false;
                        }
                    }
                    table.bootstrapTable('refresh');
                }, function (data, ret) {
                    var error = $(element).data("error") || $.noop;
                    if (typeof error === 'function') {
                        if (false === error.call(element, data, ret)) {
                            return false;
                        }
                    }
                });
            };
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                dblClickToEdit: false,
                // showExport: false,
                // exportTypes: ['excel'],
                // showColumns: false,
                pageSize: 20,
                pageList: [20, 50],
                columns: [
                    [
                        /*{checkbox: true},*/
                        {
                            field: 'id',
                            title: __('Id')
                        },
                        /*{field: 'admin_id', title: __('Admin_id')},*/
                        {
                            field: 'admin.nickname',
                            title: __('所属用户'),
                            // formatter: Table.api.formatter.label,
                            visible: requirejs.s.contexts._.config.config.admined
                        },
                        {
                            field: 'name',
                            title: __('Name')
                        },
                        {
                            field: 'saler_group_name',
                            title: __('客户群组')
                        },
                        {
                            field: 'speech.name',
                            title: __('话术名称')
                        },{
                            field: 'createtime',
                            title: __('Createtime'),
                            visible:false,
                            formatter:function(value){
                                function timestampToTime(timestamp) {
                                    var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
                                    Y = date.getFullYear() + '-';
                                    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
                                    D = date.getDate() + ' ';
                                    h = date.getHours() + ':';
                                    m = date.getMinutes() + ':';
                                    s = date.getSeconds();
                                    return Y+M+D+h+m+s;
                                }
                              return timestampToTime(value)
                                
                            }
                        },
                        {
                            field: 'gateway_name',
                            title: __('Gateway_name')
                        },
                        {
                            field: 'id',
                            title: __('Time'),
                            visible:false,
                            formatter:function(row,value,index){
                                return value.start + '-' +value.stop
                            }
                        },
                        /*{field: 'task_file', title: __('Task_file')},
                        {field: 'callback_type', title: __('Callback_type'), visible:false, searchList: {"transfer":__('callback_type transfer'),"ivr":__('callback_type ivr'),"ivr_transfer":__('callback_type ivr_transfer')}},
                        {field: 'callback_type_text', title: __('Callback_type'), operate:false},*/
                        /*{field: 'sound_id', title: __('Sound_id')},*/
                        //{field: 'sound.name', title: __('Sound_id')},
                        {
                            field: 'progress',
                            title: __('Progress'),
                            operate: false
                        },
                        /*{field: 'status', title: __('Status'), formatter: Table.api.formatter.status},*/
                        /*{field: 'state', title: __('State'), visible:false, searchList: {"0":__('State 0'),"1":__('State 1'),"2":__('State 2')}},*/
                        {
                            field: 'state_text',
                            title: __('状态'),
                            operate: false,
                            formatter: function (value, row, index) {
                                var html = '';
                                switch (value) {
                                    case '正常':
                                        html = '<span class="text-info"><i class="fa fa-play"></i> ' + __(value) + '</span>';
                                        break;
                                    case '暂停':
                                        html = '<span class="text-danger"><i class="fa fa-pause"></i> ' + __(value) + '</span>';
                                        break;
                                    case '停止':
                                        html = '<span class="text-grey"><i class="fa fa-stop"></i> ' + __(value) + '</span>';
                                        break;
                                }
                                return html;
                                //颜色状态数组,可使用red/yellow/aqua/blue/navy/teal/olive/lime/fuchsia/purple/maroon
                                var colorArr = {
                                    '正常': 'info',
                                    hidden: 'grey',
                                    deleted: 'danger',
                                    locked: 'info'
                                };
                                //如果字段列有定义custom
                                if (typeof this.custom !== 'undefined') {
                                    colorArr = $.extend(colorArr, this.custom);
                                }
                                value = value === null ? '' : value.toString();
                                var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
                                value = value.charAt(0).toUpperCase() + value.slice(1);
                                //渲染状态
                                var html = '<span class="text-' + color + '"><i class="fa fa-circle"></i> ' + __(value) + '</span>';
                                return html;
                            }
                        },
                        {
                            field: 'state',
                            title: __('任务控制'),
                            table: table,
                            operate: false,
                            formatter: function (value, row, index) {
                                var table = this.table;
                                // 操作配置
                                var options = table ? table.bootstrapTable('getOptions') : {};
                                var buttons = [];
                                if ('02'.indexOf(value) != -1) {
                                    buttons.push({
                                        name: 'start_task',
                                        icon: 'fa fa-play',
                                        title: __('开始'),
                                        extend: 'data-toggle="tooltip"',
                                        classname: 'btn-td btn-start-task',
                                        url: options.extend.start_task_url
                                    });
                                }
                                if ('1'.indexOf(value) != -1) {
                                    buttons.push({
                                        name: 'pause_task',
                                        icon: 'fa fa-pause',
                                        title: __('暂停'),
                                        extend: 'data-toggle="tooltip"',
                                        classname: 'btn-td btn-pause-task',
                                        url: options.extend.pause_task_url
                                    });
                                }
                                if ('012'.indexOf(value) != -1) {
                                    buttons.push({
                                        name: 'stop_task',
                                        icon: 'fa fa-stop',
                                        title: __('停止'),
                                        extend: 'data-toggle="tooltip"',
                                        classname: 'btn-td btn-stop-task',
                                        url: options.extend.stop_task_url
                                    });
                                }
                                //console.log(buttons);
                                return Table.api.buttonlink(this, buttons, value, row, index, 'operate');
                                return value;
                            },
                            events: {
                                'click .btn-stop-task': function (e, value, row, index) {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    var that = this;
                                    var top = $(that).offset().top - $(window).scrollTop();
                                    var left = $(that).offset().left - $(window).scrollLeft() - 260;
                                    if (top + 154 > $(window).height()) {
                                        top = top - 154;
                                    }
                                    if ($(window).width() < 480) {
                                        top = left = undefined;
                                    }
                                    Layer.confirm(
                                        __('确定停止该任务?'), {
                                            icon: 3,
                                            title: __('Warning'),
                                            offset: [top, left],
                                            shadeClose: true
                                        },
                                        function (index) {
                                            var table = $(that).closest('table');
                                            var options = table.bootstrapTable('getOptions');
                                            //Table.api.multi("stop", row[options.pk], table, that);
                                            multi("stop", row[options.pk], table, that);
                                            Layer.close(index);
                                        }
                                    );
                                },
                                'click .btn-pause-task': function (e, value, row, index) {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    var options = table.bootstrapTable('getOptions');
                                    multi("pause", row[options.pk], table, this);
                                },
                                'click .btn-start-task': function (e, value, row, index) {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    var options = table.bootstrapTable('getOptions');
                                    if (('2' != value) || ('0%' == row['progress'])) {
                                        multi("start", row[options.pk], table, this);
                                    } else {
                                        var that = this;
                                        var top = $(that).offset().top - $(window).scrollTop();
                                        var left = $(that).offset().left - $(window).scrollLeft() - 260;
                                        if (top + 154 > $(window).height()) {
                                            top = top - 154;
                                        }
                                        if ($(window).width() < 480) {
                                            top = left = undefined;
                                        }
                                        Layer.confirm(
                                            __('该任务已停止，<br/>重新开始将清除当前进度！<br/>是否继续?'), {
                                                icon: 3,
                                                title: __('Warning'),
                                                offset: [top, left],
                                                shadeClose: true
                                            },
                                            function (index) {
                                                var table = $(that).closest('table');
                                                var options = table.bootstrapTable('getOptions');
                                                multi("start", row[options.pk], table, that);
                                                Layer.close(index);
                                            }
                                        );
                                    }
                                },
                            }
                        },
                        {
                            field: 'sub_status',
                            title: __('消息推送'),
                            table: table,
                            operate: false,
                            // formatter: function (value, row, index) {
                            //     return '<a href="' + value + '" target="_blank" class="fa fa-id-badge btn-wechart" style="width: 20px; height: 20px;"></a>';
                            // }
                            formatter: function (value, row, index) {
                                var table = this.table;
                                // 操作配置
                                var options = table ? table.bootstrapTable('getOptions') : {};
                                var buttons = [];
                                if (value == 0) {
                                    buttons.push({
                                        name: 'start_task',
                                        icon: 'fa fa-weixin',
                                        title: __('扫描二维码'),
                                        extend: 'data-toggle="tooltip"',
                                        classname: 'btn-td btn-add-wechart'
                                    });
                                } else if (value == 1) {
                                    buttons.push({
                                        name: 'start_task',
                                        icon: 'fa fa-weixin',
                                        title: __(''),
                                        extend: 'data-toggle="tooltip"',
                                        classname: 'btn-td btn-no-untie'
                                    });
                                }
                                return Table.api.buttonlink(this, buttons, value, row, index, 'operate');
                                return value;
                            },
                            events: {
                                'click .btn-add-wechart': function (e, value, row, index) {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    var that = this;
                                    var $that = $(this);
                                    var top = $(that).offset().top - $(window).scrollTop();
                                    var left = $(that).offset().left - $(window).scrollLeft() - 260;
                                    if (top + 154 > $(window).height()) {
                                        top = top - 154;
                                    }
                                    if ($(window).width() < 480) {
                                        top = left = undefined;
                                    }
                                    if (row.sub_status == 0) {
                                        layer.msg(' ', {
                                            skin: 'winning-class',
                                            time: 0,
                                            title: false,
                                            btnAlign: 'c',
                                            area: ['26rem', '30rem'],
                                            btn: ['确定'],
                                            content: '<img src=' + row.wx_url + ' style="width: 100%; height: 100%;"/>',
                                            yes: function (index) {
                                                $.post("/admin/task/task/tasksub?taskId=" + row.id + "", function (data) {
                                                    if (data.code == "1" || data.code == "200") {
                                                        Toastr.success(data.msg);
                                                        table.bootstrapTable('refresh');
                                                    } else {
                                                        Toastr.error(data.msg);
                                                    }
                                                    Layer.close(index);
                                                });
                                            }
                                        });
                                    }
                                }
                            }
                        },
                        {
                            field: 'task_sub',
                            title: __('订阅状态'),
                            operate: false,
                            table: table,
                            formatter: function (value, row, index) {
                                var table = this.table;
                                // 操作配置
                                var options = table ? table.bootstrapTable('getOptions') : {};
                                var buttons = [];
                                if (value == 0) {
                                    buttons.push({
                                        name: 'start_task',
                                        icon: 'fa fa-minus-square',
                                        title: __('未订阅'),
                                        extend: 'data-toggle="tooltip"',
                                        classname: 'btn-td btn-no-untie'
                                    });
                                } else if (value == 1) {
                                    buttons.push({
                                        name: 'start_task',
                                        icon: 'fa fa-check-square',
                                        title: __('已订阅'),
                                        extend: 'data-toggle="tooltip"',
                                        classname: 'btn-td btn-untie'
                                    });
                                }
                                return Table.api.buttonlink(this, buttons, value, row, index, 'operate');
                                return value;
                            },
                            events: {
                                'click .btn-untie': function (e, value, row, index) {
                                    var that = this;
                                    var $that = $(this);
                                    var top = $(that).offset().top - $(window).scrollTop();
                                    var left = $(that).offset().left - $(window).scrollLeft() - 260;
                                    if (top + 154 > $(window).height()) {
                                        top = top - 154;
                                    }
                                    if ($(window).width() < 480) {
                                        top = left = undefined;
                                    }
                                    if (row.task_sub == 1) {
                                        Layer.confirm(
                                            __('确定取消订阅?'), {
                                                icon: 3,
                                                title: __('Warning'),
                                                offset: [top, left],
                                                shadeClose: true
                                            },
                                            function (index) {
                                                $.post("/admin/task/task/unSubTask?taskId=" + row.id + "", function (data) {
                                                    layer.close(index);
                                                    if (data.code == "200") {
                                                        $that.addClass('btn-untie').removeClass('btn-no-untie');
                                                        Toastr.success(data.msg);
                                                        table.bootstrapTable('refresh');
                                                    }
                                                });
                                            }
                                        );
                                    }
                                }
                            }
                        },
                        {
                            field: 'success_count',
                            title: __('呼叫总数/已完成/成功'),
                            table: table,
                            formatter: function (value, row, index) {
                                return '<span>' +row.total_count + '/' +row.done_count + '/' + value + '</span>';
                            }
                        },
                        {
                            field: 'fail_count',
                            title: __('失败'),
                            table: table,
                            formatter: function (value, row, index) {
                                if (value <= 0) {
                                    return value;
                                }
                                if ('2' != row['state']) {
                                    return value;
                                }
                                var table = this.table;
                                // 操作配置
                                var options = table ? table.bootstrapTable('getOptions') : {};
                                var buttons = [];
                                // console.log(options);
                                buttons.push({
                                    name: 'retry_task',
                                    icon: 'fa fa-undo',
                                    title: __('重试'),
                                    extend: 'data-toggle="tooltip"',
                                    classname: 'btn-td btn-retry-task',
                                    url: options.extend.retry_task_url
                                });
                                return value + ' ' + Table.api.buttonlink(this, buttons, value, row, index, 'operate');
                            },
                            events: {
                                'click .btn-retry-task': function (e, value, row, index) {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    var options = table.bootstrapTable('getOptions');
                                    multi("retry", row[options.pk], table, this);
                                },
                            }
                        },
                        //{field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        /*{field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},*/
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: function (value, row, index) {
                                var that = $.extend({}, this);
                                var table = $(that.table).clone(true);
                                if (row.done_count > 0) {
                                    $(table).data("operate-edit", null);
                                    $(table).data("operate-del", null);
                                }
                                that.table = table;
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }
                        }
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            layui.use('laydate', function datatime() {
                var laydate = layui.laydate;
                //日期时间
                laydate.render({
                    elem: '#start',
                    type: 'time' ,
                    format: 'HH:mm',
                    min: '9:00:00',
                    max: '20:00:00',
                    btns: ['clear', 'confirm'],
                    calendar: true,
                    done: function (value, date, endDate) {
                        $('#stop').val('');
                        end.config.min = {
                            year: date.year,
                            month: date.month - 1,
                            date: date.date,
                            hours: date.hours,
                            minutes: date.minutes,
                            seconds: date.seconds
                        }
                    }
                });
                var end = laydate.render({
                    elem: '#stop',
                    type: 'time',
                    format: 'HH:mm',
                    max: '20:00:00',
                    calendar: true,
                    btns: ['clear', 'confirm']
                });
            });
            Controller.api.bindevent();
        },
        edit: function () {
            layui.use('laydate', function datatime() {
                var laydate = layui.laydate;
                //日期时间
                laydate.render({
                    elem: '#start',
                    type: 'time',
                    format: 'HH:mm',
                    min: '9:00:00',
                    max: '20:00:00',
                    btns: ['clear', 'confirm'],
                    calendar: true,
                    done: function (value, date, endDate) {
                        $('#stop').val('');
                        end.config.min = {
                            year: date.year,
                            month: date.month - 1,
                            date: date.date,
                            hours: date.hours,
                            minutes: date.minutes,
                            seconds: date.seconds
                        }
                    }
                });
                var end = laydate.render({
                    elem: '#stop',
                    type: 'time',
                    format: 'HH:mm',
                    max: '20:00:00',
                    calendar: true,
                    btns: ['clear', 'confirm']
                });
            });
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});